package com.mytinyRPC.serializer.Impl;

import com.alibaba.fastjson.JSONObject;
import com.mytinyRPC.exception.SerializeException;
import com.mytinyRPC.framework.Invocation;
import com.mytinyRPC.serializer.CommonSerializer;

import java.io.IOException;

/***
 * @Author HP
 * @Description //TODO JSON序列化和反序列化类
 **/
public class JsonSerializer implements CommonSerializer {
    @Override
    public byte[] serialize(Object obj) {
        return JSONObject.toJSONBytes(obj);
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz) {
        try{
        Object obj=JSONObject.parseObject(bytes,clazz);
        if (obj instanceof Invocation) {
            obj = handleRequest(obj);
        }
        return obj;
        } catch (IOException e) {
            System.out.println("序列化时有错误发生:"+e);
            throw new SerializeException("序列化时有错误发生");
        }
    }

    @Override
    public int getCode() {
        return 1;
    }

    /*
        这里由于使用JSON序列化和反序列化Object数组，无法保证反序列化后仍然为原实例类型
        需要重新判断处理
     */
    private Object handleRequest(Object obj) throws IOException {
        Invocation invocation = (Invocation) obj;
        for (int i = 0; i < invocation.getParamTypes().length; i++) {
            Class<?> clazz = invocation.getParamTypes()[i];
            if (!clazz.isAssignableFrom(invocation.getParams()[i].getClass())) {
                byte[] bytes = JSONObject.toJSONBytes(invocation.getParams()[i]);
                invocation.getParams()[i] = JSONObject.parseObject(bytes, clazz);
            }
        }
        return invocation;
    }
}
